// pages/detail/detail.js
const http = require('../../utils/http')
const config = require('../../utils/config')
const util = require('../../utils/util')
const api = require('../../utils/extendApi')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopId: 1,
    userId: 1,
    data: {},
    comments: [],
    commentsAll: [],
    parameters: [],
    parametersString: [],
    prodNum: 1,
    inCart: false,
    cartItem: null,


    picDomain: config.picDomain,
    indicatorDots: true,
    indicatorColor: '#f2f2f2',
    indicatorActiveColor: '#eb2444',
    autoplay: true,
    interval: 3000,
    duration: 1000,
    totalCartNum: 0,
    pic: "",
    imgs: '',
    prodName: '',
    price: 0,
    content: '',
    goodsId: 0,
    brief: '',
    skuId: 0,
    popupShow: false,
    // 是否获取过用户领取过的优惠券id
    loadCouponIds: false,
    skuShow: false,
    commentShow: false,
    couponList: [],
    skuList: [],
    skuGroup: {},
    findSku: true,
    defaultSku: undefined,
    selectedProp: [],
    selectedPropObj: {},
    propKeys: [],
    allProperties: [],
    prodCommData: {},
    prodCommPage: {
      current: 0,
      pages: 0,
      records: []
    },
    littleCommPage: [],
    evaluate: -1,
    isCollection: false,
    collectionId: 0,
  },
  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {

    // 获取商品的详情数据
    this.getGoodDetail()
    // 加载评论的数据
    this.getProdCommData()
    // 加载全部评论的数据
    this.getCommentAll()
    console.log("登录？", await util.isLoginAns())
    if (! await util.isLoginAns()) {
      api.toast({
        title: '未登录，请登录',
      });
      return;
    } else {
      // 获取商品是否存在收藏列表中
      this.getCollection()
      // 是否在购物车中
      this.getInCart()
      // 添加足迹
      this.addHistory()
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const userId = wx.getStorageSync('userId');
    this.setData({
      goodsId: Number(options.prodId),
      userId: userId
    })
  },
  getInCart() {
    var page = this
    var params = {
      url: "/cart",
      method: "GET",
      data: {
        goodsId: page.data.goodsId,
        userId: page.data.userId
      },
      callBack(res) {
        if (res && res.length > 0) {
          console.log("在购物车", res)
          page.setData({
            inCart: true,
            cartItem: res[0]
          })
        }
      },
      errCallBack(res) {}
    }
    http.request(params)
  },
  getGoodDetail() {
    var page = this
    var params = {
      url: "/goods?id=" + this.data.goodsId,
      method: "GET",
      data: {},
      callBack(res) {
        let ids = res[0].configurationList.map(item => item.parameterList[0].id);
        let paramString = res[0].configurationList.map(item => item.parameterList[0].content);
        page.setData({
          data: res[0],
          parameters: ids,
          parametersString: paramString
        })
      },
      errCallBack(res) {}
    }
    http.request(params)
  },

  /**
   * 添加浏览记录
   */
  addHistory(e) {
    var params = {
      url: "/history",
      method: "POST",
      data: {
        userId: this.data.userId,
        goodsId: this.data.goodsId
      },
      callBack: (res) => {
        console.log("浏览记录------", res)
      },
      errCallBack(res) {}
    }
    http.request(params)
  },



  /**
   * 整合SKU数据
   */
  groupSkuProp() {
    var skuList = this.data.skuList;

    //当后台返回只有一个SKU时，且SKU属性值为空时，即该商品没有规格选项，该SKU直接作为默认选中SKU
    if (skuList.length == 1 && skuList[0].properties == "") {
      this.setData({
        defaultSku: skuList[0]
      });
      return;
    }

    var skuGroup = {}; //所有的规格名(包含规格名下的规格值集合）对象，如 {"颜色"：["金色","银色"],"内存"：["64G","256G"]}
    var allProperties = []; //所有SKU的属性值集合，如 ["颜色:金色;内存:64GB","颜色:银色;内存:64GB"]
    var propKeys = []; //所有的规格名集合，如 ["颜色","内存"]

    for (var i = 0; i < skuList.length; i++) {

      //找到和商品价格一样的那个SKU，作为默认选中的SKU
      var defaultSku = this.data.defaultSku;
      var isDefault = false;
      if (!defaultSku && skuList[i].price == this.data.price) {
        defaultSku = skuList[i];
        isDefault = true;
        this.setData({
          defaultSku: defaultSku
        });
      }

      var properties = skuList[i].properties; //如：版本:公开版;颜色:金色;内存:64GB
      allProperties.push(properties);
      var propList = properties.split(";"); // 如：["版本:公开版","颜色:金色","内存:64GB"]

      var selectedPropObj = this.data.selectedPropObj;
      for (var j = 0; j < propList.length; j++) {

        var propval = propList[j].split(":"); //如 ["版本","公开版"]
        var props = skuGroup[propval[0]]; //先取出 规格名 对应的规格值数组

        //如果当前是默认选中的sku，把对应的属性值 组装到selectedProp
        if (isDefault) {
          propKeys.push(propval[0]);
          selectedPropObj[propval[0]] = propval[1];
        }

        if (props == undefined) {
          props = []; //假设还没有版本，新建个新的空数组
          props.push(propval[1]); //把 "公开版" 放进空数组
        } else {
          if (!this.array_contain(props, propval[1])) { //如果数组里面没有"公开版"
            props.push(propval[1]); //把 "公开版" 放进数组
          }
        }
        skuGroup[propval[0]] = props; //最后把数据 放回版本对应的值
      }
      this.setData({
        selectedPropObj: selectedPropObj,
        propKeys: propKeys
      });
    }
    this.parseSelectedObjToVals();
    this.setData({
      skuGroup: skuGroup,
      allProperties: allProperties
    });

  },


  /***
   * 把已选的{key：val，key2：val2} 转换成 [val,val2]
   */
  parseSelectedObjToVals() {
    // 选中的属性
    var selectedPropObj = this.data.selectedPropObj
    var selectProperties = ''
    var selectedProp = []

    for (const key in selectedPropObj) {
      selectedProp.push(selectedPropObj[key])
      selectProperties += key + ':' + selectedPropObj[key] + ";"
    }

    selectProperties = selectProperties.substring(0, selectProperties.length - 1)
    this.setData({
      selectedProp: selectedProp
    })

    var findSku = false
    for (let i = 0; i < this.data.skuList.length; i++) {
      if (this.data.skuList[i].properties == selectProperties) {
        findSku = true;
        this.setData({
          defaultSku: this.data.skuList[i]
        })
        break
      }
    }
    this.setData({
      findSku: findSku
    })
  },
  //点击选择规格
  toChooseItem: function (e) {
    var index = e.currentTarget.dataset.index;
    var val = e.currentTarget.dataset.val;
    var key = e.currentTarget.dataset.key;
    var parameters = this.data.parameters
    var parametersString = this.data.parametersString
    parameters[index] = key
    parametersString[index] = val
    this.setData({
      parameters: parameters,
      parametersString: parametersString
    });
    console.log(index, this.data.parameters, this.data.parametersString)

    var selectedPropObj = this.data.selectedPropObj;
    selectedPropObj[key] = val;
    this.setData({
      selectedPropObj: selectedPropObj
    });
    this.parseSelectedObjToVals();
  },

  //判断数组是否包含某对象
  array_contain: function (array, obj) {
    for (var i = 0; i < array.length; i++) {
      if (array[i] == obj) //如果要求数据类型也一致，这里可使用恒等号===
        return true;
    }
    return false;
  },



  /***
   * 获取商品是否存在于收藏夹中
   */
  getCollection() {
    var page = this
    console.log("userid:", page.data.userId)
    console.log("goodsId", page.data.goodsId)
    var params = {
      url: "/collect",
      method: "GET",
      data: {
        userId: page.data.userId,
        goodsId: page.data.goodsId
      },
      callBack(res) {
        console.log("收藏", res)
        if (res && res.length == 0) {
          page.setData({
            isCollection: false
          })
        } else {
          page.setData({
            isCollection: true,
            collectionId: res[0].id
          })
        }
      },
      errCallBack(res) {}
    }
    http.request(params)
  },

  /***
   * 更新商品的收藏状态
   * 添加或取消商品的收藏
   */
  addOrCancleCollection() {
    util.isLogin()
    wx.showLoading()
    if (this.data.isCollection) {
      // 取消收藏
      var page = this
      console.log("取消收藏", page.data.collectionId)
      var params = {
        url: '/collect?id=' + page.data.collectionId,
        method: "DELETE",
        callBack(res) {
          page.setData({
            isCollection: !page.data.isCollection
          })
          wx.hideLoading()
        },
        errCallBack(res) {}
      }
      console.log(params);
      http.request(params)
    } else {
      // 添加收藏
      console.log("添加收藏")
      var page = this
      var params = {
        url: '/collect',
        method: "POST",
        data: {
          "userId": page.data.userId,
          "goodsId": page.data.goodsId
        },
        callBack(res) {
          page.setData({
            collectionId: res.id,
            isCollection: !page.data.isCollection
          })
          wx.hideLoading()
        },
        errCallBack(res) {}
      }
      console.log(params);
      http.request(params)
    }
  },
  /***
   * 获取评论的数据
   */
  getProdCommData() {
    console.log("/comment/page?page=1&pageSize=3&goodsId=" + this.data.goodsId)
    var page = this
    var params = {
      url: "/comment/page?page=1&pageSize=3&goodsId=" + this.data.goodsId,
      method: "GET",
      data: {},
      callBack(res) {
        page.setData({
          comments: res
        })
      },
      errCallBack(res) {}
    }
    http.request(params)
  },
  getCommentAll() {
    var page = this
    var params = {
      url: "/comment?goodsId=" + this.data.goodsId,
      method: "GET",
      data: {},
      callBack(res) {
        page.setData({
          commentsAll: res
        })
      },
      errCallBack(res) {}
    }
    http.request(params)
  },

  /***
   * 获取分页评论数据
   */
  getProdCommPage(e) {
    if (e) {
      if (e.currentTarget.dataset.evaluate === this.data.evaluate) {
        return;
      }
      this.setData({
        prodCommPage: {
          current: 0,
          pages: 0,
          records: []
        },
        evaluate: e.currentTarget.dataset.evaluate
      })
    }
    http.request({
      url: config.prodCommPageByProdUrl,
      method: "GET",
      data: {
        goodsId: this.data.goodsId,
        size: 10,
        current: this.data.prodCommPage.current + 1,
        evaluate: this.data.evaluate
      },
      callBack: (res) => {
        res.records.forEach(item => {
          if (item.pics) {
            item.pics = item.pics.split(',')
          }
        })
        let records = this.data.prodCommPage.records
        records = records.concat(res.records)
        this.setData({
          prodCommPage: {
            current: res.current,
            pages: res.pages,
            records: records
          }
        })
        // 如果商品详情中没有评论的数据，截取两条到商品详情页商品详情
        if (!this.data.littleCommPage.length) {
          this.setData({
            littleCommPage: records.slice(0, 2)
          })
        }
      }
    })
  },

  /***
   * 跳转到首页
   */
  toHomePage() {
    wx.switchTab({
      url: '../index/index',
    })

  },
  /***
   * 跳转到购物车
   */
  toCartPage() {
    wx.switchTab({
      url: '../basket/basket',
    })

  },


  /***
   * 加入购物车
   */
  addToCart() {
    util.isLogin()
    var page = this
    if (this.data.inCart) {
      console.log("购物车中：", page.data.cartItem)
      var params = {
        url: '/cart',
        method: "PUT",
        data: {
          id: page.data.cartItem.id,
          status: 0,
          userId: page.data.userId,
          parameterId: page.data.parameters.join(','),
          total: page.data.cartItem.total + page.data.prodNum,
          goodsId: page.data.goodsId,
          parameters: page.data.parametersString.join(',')
        },
        callBack(res) {
          console.log(res);
          api.toast({
            title: "添加成功",
            icon: 'success'
          })
        },
        errCallBack(res) {}
      }
      http.request(params)
    } else {
      var params = {
        url: '/cart',
        method: "POST",
        data: {
          status: 0,
          userId: page.data.userId,
          parameterId: page.data.parameters.join(','),
          total: page.data.prodNum,
          goodsId: page.data.goodsId,
          parameters: page.data.parametersString.join(',')
        },
        callBack(res) {
          console.log(res);
          api.toast({
            title: "添加成功",
            icon: 'success'
          })
          page.setData({
            inCart: true,
            cartItem: res
          })
          console.log("添加成功 cartItem:", page.data.cartItem)
        },
        errCallBack(res) {}
      }
      http.request(params)
    }
  },

  /**
   * 立即购买
   */
  buyNow: function () {
    util.isLogin()
    if (!this.data.findSku) {
      return;
    }
    wx.setStorageSync("orderItem", JSON.stringify({
      goodsId: this.data.goodsId,
      skuId: this.data.defaultSku.skuId,
      prodCount: this.data.prodNum,
      shopId: this.data.shopId
    }));
    wx.navigateTo({
      url: '/pages/submit-order/submit-order?orderEntry=1',
    })

  },

  onCountMinus() {
    var num = this.data.prodNum - 1
    if (num < 1)
      num = 1
    this.setData({
      prodNum: num
    })
  },
  onCountPlus() {
    this.setData({
      prodNum: this.data.prodNum + 1
    })
  },
  /***
   * 显示弹窗
   */
  showSku: function () {
    this.setData({
      skuShow: true
    })
  },
  showComment: function () {
    this.getCommentAll()
    this.setData({
      commentShow: true
    });
  },
  /***
   * 关闭弹窗
   */
  closePopup: function () {
    this.setData({
      skuShow: false,
      commentShow: false
    })
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})